package com.nari.ncps.screen.service.impl.al;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.al.AlProdoperPrdQual;
import com.nari.ncps.screen.entity.al.AlProdoperPrdQualTsyj;
import com.nari.ncps.screen.entity.al.AlProdoperStock;
import com.nari.ncps.screen.mapper.al.AlProdoperPrdQualMapper;
import com.nari.ncps.screen.mapper.al.AlProdoperPrdQualTsyjMapper;
import com.nari.ncps.screen.service.al.AlProdoperPrdQualService;
import com.nari.ncps.screen.vo.al.AlProdoperPrdQualOneVO;
import com.nari.ncps.screen.vo.al.AlProdoperPrdQualThreeVO;
import com.nari.ncps.screen.vo.al.AlProdoperPrdQualTwoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 生产质量表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class AlProdoperPrdQualServiceImpl extends ServiceImpl<AlProdoperPrdQualMapper, AlProdoperPrdQual> implements AlProdoperPrdQualService {

    @Autowired
    private AlProdoperPrdQualTsyjMapper alProdoperPrdQualTsyjMapper;

    @Override
    public List<AlProdoperPrdQualOneVO> getAluminumQualityData() {
//        // 获取当前日期
//        LocalDate currentDate = LocalDate.now();
//        LocalDate startDate = currentDate.minusMonths(11);
//        int startDateYear = startDate.getYear();//上一年
//        int startDateMonth = startDate.getMonth().getValue();//上一年的月
//
//        // 先从数据库查询最近12个月的数据
////        QueryWrapper<AlProdoperPrdQual> queryWrapper = new QueryWrapper<>();
////        queryWrapper.ge("year", startDate.getYear())
////                   .orderByAsc("year", "month");
////
////        List<AlProdoperPrdQual> qualList = this.list(queryWrapper);
//
//        LambdaQueryWrapper<AlProdoperPrdQual> wrapper = Wrappers.lambdaQuery();
//        wrapper.eq(AlProdoperPrdQual::getDateType, 1)
//                .eq(AlProdoperPrdQual::getOrgCode, 100360)
//                .eq(AlProdoperPrdQual::getPruductRateType, 4)//产品类型：3-铝液;4-低铁铝率
//                .between(AlProdoperPrdQual::getStatisticTime, lastYearSameMonth,currentYearMonth)
//                .orderByDesc(AlProdoperPrdQual::getStatisticTime);
//        List<AlProdoperPrdQual> qualList = this.list(wrapper);

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        LocalDate startDate = currentDate.minusMonths(11);

        LocalDate startDate2 = currentDate.minusMonths(22);

        // 获取当前年月
        String currentYearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));

        // 获取去年同期年月（减去1年）
        String lastYearSameMonth = startDate.format(DateTimeFormatter.ofPattern("yyyyMM"));

        // 获取去年同期年月（减去1年）
        String lastYearSameMonth2 = startDate2.format(DateTimeFormatter.ofPattern("yyyyMM"));


        // 近12个月的日期
        LocalDate months = currentDate.minusMonths(11);

        // 查询最近12个月的数据
        LambdaQueryWrapper<AlProdoperPrdQual> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AlProdoperPrdQual::getDateType, 1)
                .eq(AlProdoperPrdQual::getOrgCode, 100360)
                .eq(AlProdoperPrdQual::getProductRateType, 3)//产品类型：3-铝液;4-低铁铝率
                .between(AlProdoperPrdQual::getStatisticTime, lastYearSameMonth,currentYearMonth)
                .orderByDesc(AlProdoperPrdQual::getStatisticTime);
        List<AlProdoperPrdQual> qualList = this.list(wrapper);
        
        // 如果数据库中没有数据，返回mock数据
        if (qualList == null || qualList.isEmpty()) {
            return generateMockAluminumQualityData(currentDate);
        }
        
        // 转换为VO对象
        List<AlProdoperPrdQualOneVO> voList = new ArrayList<>();
        for (AlProdoperPrdQual entity : qualList) {
//            if(entity.getMonth()!=null && ((entity.getYear()==startDateYear && entity.getMonth()>=startDateMonth) || entity.getYear()>startDateYear)) {
//            }
            AlProdoperPrdQualOneVO vo = new AlProdoperPrdQualOneVO();
            vo.setYear(entity.getYear());
            vo.setMonth(entity.getMonth());
            vo.setDay(entity.getDay());
            vo.setAlCurrentQualityRate(entity.getAlCurrentQualityRate());
            vo.setAlYoyQualityRate(entity.getAlYoyQualityRate());
            voList.add(vo);
        }

        // 查询去年同期12个月的数据
        LambdaQueryWrapper<AlProdoperPrdQual> wrapper2 = Wrappers.lambdaQuery();
        wrapper2.eq(AlProdoperPrdQual::getDateType, 1)
                .eq(AlProdoperPrdQual::getOrgCode, 100360)
                .eq(AlProdoperPrdQual::getProductRateType, 3)//产品类型：3-铝液;4-低铁铝率
                .between(AlProdoperPrdQual::getStatisticTime, lastYearSameMonth2,lastYearSameMonth)
                .orderByDesc(AlProdoperPrdQual::getStatisticTime);
        List<AlProdoperPrdQual> qualList2 = this.list(wrapper);

//        // 如果数据库中没有数据，返回mock数据
//        if (qualList2 == null || qualList2.isEmpty()) {
//            return generateMockAluminumQualityData(currentDate);
//        }

        // 转换为VO对象
        List<AlProdoperPrdQualOneVO> voList2 = new ArrayList<>();
        for (AlProdoperPrdQual entity : qualList2) {
//            if(entity.getMonth()!=null && ((entity.getYear()==startDateYear && entity.getMonth()>=startDateMonth) || entity.getYear()>startDateYear)) {
//            }
            AlProdoperPrdQualOneVO vo = new AlProdoperPrdQualOneVO();
            vo.setYear(entity.getYear());
            vo.setMonth(entity.getMonth());
            vo.setDay(entity.getDay());
            vo.setAlCurrentQualityRate(entity.getAlCurrentQualityRate());
            vo.setAlYoyQualityRate(entity.getAlYoyQualityRate());
            voList.add(vo);
        }
        
        return voList;
    }
    
    /**
     * 生成mock铝产量质量数据（最近12个月）
     * 覆盖全场景：包括品率波动、季节性变化、同比差异等
     */
    private List<AlProdoperPrdQualOneVO> generateMockAluminumQualityData(LocalDate currentDate) {
        List<AlProdoperPrdQualOneVO> mockData = new ArrayList<>();
        
        // 生成最近12个月的数据
        for (int i = 11; i >= 0; i--) {
            LocalDate monthDate = currentDate.minusMonths(i);
            AlProdoperPrdQualOneVO vo = new AlProdoperPrdQualOneVO();
            vo.setYear(monthDate.getYear());
            vo.setMonth(monthDate.getMonthValue());
            vo.setDay(1);
            
            // 当期品率：基础值98.5%，随机波动 ±1.5%
            // 模拟不同场景：1-3月冬季较低，7-9月夏季较高，其他月份正常
            BigDecimal baseRate = new BigDecimal("98.50");
            double seasonalFactor = 0.0;
            int month = monthDate.getMonthValue();
            
            if (month >= 1 && month <= 3) {
                // 冬季：品率略低
                seasonalFactor = -0.8 + (Math.random() * 0.6); // -0.8 to -0.2
            } else if (month >= 7 && month <= 9) {
                // 夏季：品率较高
                seasonalFactor = 0.3 + (Math.random() * 0.8); // 0.3 to 1.1
            } else {
                // 春秋：正常波动
                seasonalFactor = -0.3 + (Math.random() * 0.6); // -0.3 to 0.3
            }
            
            BigDecimal currentRate = baseRate.add(new BigDecimal(seasonalFactor));
            vo.setAlCurrentQualityRate(currentRate.setScale(2, RoundingMode.HALF_UP));
            
            // 同期品率：比当期品率略低0.5-2%（体现技术进步）
            BigDecimal yoyDiff = new BigDecimal(0.5 + Math.random() * 1.5);
            BigDecimal yoyRate = currentRate.subtract(yoyDiff);
            vo.setAlYoyQualityRate(yoyRate.setScale(2, RoundingMode.HALF_UP));
            
            mockData.add(vo);
        }
        
        return mockData;
    }

    @Override
    public List<AlProdoperPrdQualTwoVO> getLowIronAluminumRateData() {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        LocalDate startDate = currentDate.minusMonths(11);
        LocalDate startDate2 = currentDate.minusMonths(22);

        // 获取当前年月
        String currentYearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));

        // 获取去年同期年月（减去1年）
        String lastYearSameMonth = startDate.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String lastYearSameMonth2 = startDate2.format(DateTimeFormatter.ofPattern("yyyyMM"));


        // 近12个月的日期
        LocalDate months = currentDate.minusMonths(11);

        // 查询最近12个月的数据
        LambdaQueryWrapper<AlProdoperPrdQual> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AlProdoperPrdQual::getDateType, 1)
                .eq(AlProdoperPrdQual::getOrgCode, 100360)
                .eq(AlProdoperPrdQual::getProductRateType, 4)//产品类型：3-铝液;4-低铁铝率
                .between(AlProdoperPrdQual::getStatisticTime, lastYearSameMonth,currentYearMonth)
                .orderByDesc(AlProdoperPrdQual::getStatisticTime);
        List<AlProdoperPrdQual> qualList = this.list(wrapper);

        // 转换为VO对象
        List<AlProdoperPrdQualTwoVO> voList = new ArrayList<>();
        for (AlProdoperPrdQual entity : qualList) {
            AlProdoperPrdQualTwoVO vo = new AlProdoperPrdQualTwoVO();
            vo.setYear(entity.getYear());
            vo.setMonth(entity.getMonth());
            vo.setDay(entity.getDay());
            vo.setLowFeAlCurrentRate(entity.getLowFeAlCurrentRate());
            vo.setLowFeAlYoyRate(entity.getLowFeAlYoyRate());
            voList.add(vo);
        }

        // 查询去年同期12个月的数据
        LambdaQueryWrapper<AlProdoperPrdQual> wrapper2 = Wrappers.lambdaQuery();
        wrapper2.eq(AlProdoperPrdQual::getDateType, 1)
                .eq(AlProdoperPrdQual::getOrgCode, 100360)
                .eq(AlProdoperPrdQual::getProductRateType, 4)//产品类型：3-铝液;4-低铁铝率
                .between(AlProdoperPrdQual::getStatisticTime, lastYearSameMonth2,lastYearSameMonth)
                .orderByDesc(AlProdoperPrdQual::getStatisticTime);
        List<AlProdoperPrdQual> qualList2 = this.list(wrapper);

        // 转换为VO对象
//        List<AlProdoperPrdQualTwoVO> voList = new ArrayList<>();
        for (AlProdoperPrdQual entity : qualList2) {
            AlProdoperPrdQualTwoVO vo = new AlProdoperPrdQualTwoVO();
            vo.setYear(entity.getYear());
            vo.setMonth(entity.getMonth());
            vo.setDay(entity.getDay());
            vo.setLowFeAlCurrentRate(entity.getLowFeAlCurrentRate());
            vo.setLowFeAlYoyRate(entity.getLowFeAlYoyRate());
            voList.add(vo);
        }
        
        return voList;
    }

    /**
     *  碳素阳极质量
     * @param year 年
     * @return 月
     */
    @Override
    public List<AlProdoperPrdQualThreeVO> getCarbonAnodeQualityData(Integer year) {

        // 获取当前时间
        LocalDate now = LocalDate.now();
        int currentYear = now.getYear();
        int currentMonth = now.getMonthValue();

        // 计算过去12个月的年份和月份（包含当前月）
        List<String> statisticTimes = new ArrayList<>();
        List<String> lastYearStatisticTimes = new ArrayList<>();
        for (int i = 11; i >= 0; i--) {
            LocalDate date = now.minusMonths(i);
            String statisticTime = String.format("%d%02d", date.getYear(), date.getMonthValue());
            String lastStatisticTime = String.format("%d%02d", date.getYear()-1, date.getMonthValue());
            statisticTimes.add(statisticTime);
            lastYearStatisticTimes.add(lastStatisticTime);
        }

        // 构建查询条件
        LambdaQueryWrapper<AlProdoperPrdQualTsyj> lqw = new LambdaQueryWrapper<>();
        lqw.in(AlProdoperPrdQualTsyj::getStatisticTime, statisticTimes)
                .eq(AlProdoperPrdQualTsyj::getOrgCode, "100360")
                .eq(AlProdoperPrdQualTsyj::getDateType, 1)
                .orderByAsc(AlProdoperPrdQualTsyj::getStatisticTime);

        // 执行查询
        List<AlProdoperPrdQualTsyj> entityList = alProdoperPrdQualTsyjMapper.selectList(lqw);

        // 转换为VO列表，并确保包含所有12个月的数据
        List<AlProdoperPrdQualThreeVO> voList = new ArrayList<>();

        for (String statTime : statisticTimes) {
            // 从statistic_time解析年份和月份
            int year1 = Integer.parseInt(statTime.substring(0, 4));
            int month = Integer.parseInt(statTime.substring(4));

            // 在查询结果中查找对应的记录
            AlProdoperPrdQualTsyj entity = entityList.stream()
                    .filter(e -> statTime.equals(e.getStatisticTime()))
                    .findFirst()
                    .orElse(null);

            AlProdoperPrdQualThreeVO vo = new AlProdoperPrdQualThreeVO();
            vo.setYear(year1);
            vo.setMonth(month);
            vo.setDay(1); // 如果没有具体日期，设置为1

            if (entity != null) {
                vo.setCarbonAnodeCurrentRate(entity.getCarbonAnodeCurrentRate());
                vo.setCarbonAnodeYoyRate(entity.getCarbonAnodeYoyRate());
            } else {
                // 如果数据库中不存在该月份的数据，设置为null但保留日期信息
                vo.setCarbonAnodeCurrentRate(null);
                vo.setCarbonAnodeYoyRate(null);
            }
            voList.add(vo);
        }

        //处理同期的率值---------------------------------------------------------------------
        //处理同期的率值---------------------------------------------------------------------

        // 构建查询条件
        LambdaQueryWrapper<AlProdoperPrdQualTsyj> lqwYoY = new LambdaQueryWrapper<>();
        lqwYoY.in(AlProdoperPrdQualTsyj::getStatisticTime, lastYearStatisticTimes)
                .eq(AlProdoperPrdQualTsyj::getOrgCode, "100360")
                .eq(AlProdoperPrdQualTsyj::getDateType, 1)
                .orderByAsc(AlProdoperPrdQualTsyj::getStatisticTime);

        // 执行查询
        List<AlProdoperPrdQualTsyj> LastYearEntityList = alProdoperPrdQualTsyjMapper.selectList(lqw);
        for(AlProdoperPrdQualThreeVO lastVo : voList) {
            if(LastYearEntityList!=null && LastYearEntityList.size()>0) {
                int lastYear = lastVo.getYear()-1;
                Optional<AlProdoperPrdQualTsyj> first = LastYearEntityList.stream().filter(x -> x.getYear() == lastYear
                        && x.getMonth() == lastVo.getMonth()
                ).findFirst();
                if(first.isPresent()) {
                    BigDecimal carbonAnodeCurrentRate = first.get().getCarbonAnodeCurrentRate();
                    lastVo.setCarbonAnodeYoyRate(carbonAnodeCurrentRate.setScale(2, RoundingMode.HALF_UP));
                }
            }
        }

        return voList;
    }

}
